package com.firefighting.maintenancer;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.firefighting.entity.FirstMaintenanceProject;
import com.firefighting.util.JdbcUtils;
import com.firefighting.util.MYJSONObject;
import com.itextpdf.text.List;

import net.sf.json.JSONArray;
//import sun.misc.BASE64Decoder;

/**
 * Servlet implementation class PlanCreateTask
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/PlanCreateTask" })
public class PlanCreateTask extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		System.out.println("-----"+format.format(new Date())+"    "+this.getServletName()+"-----");
		
		String userId=request.getParameter("userId");
		String task_type=request.getParameter("task_type");
		String task_name=request.getParameter("task_name");
		String task_character=request.getParameter("task_character");
		String project_id=request.getParameter("project_id");
		String maintenanceplan_id=request.getParameter("maintenanceplan_id");
		String second_project_id=request.getParameter("second_project_id");
		String code_chosed=request.getParameter("code_chosed");
		String create_time=format.format(new Date());
		
		ArrayList<String> sp_id=new ArrayList<>();
		System.out.println(second_project_id);
		//System.out.println(sp_id.length);
		/*Base64Test base_photo=new Base64Test();
		if(base_photo.GenerateImage(photo,"123"))
			{
			
			};*/
		if(second_project_id.contains("/")) 
		{	
		String[] strings=second_project_id.split("\\/");
		for(int i=0;i<strings.length;i++)
		  {
		  sp_id.add(strings[i]);
		  }
		}
		else 
		{
			sp_id.add(second_project_id);
		}
		//BASE64Decoder decoder = new BASE64Decoder();
		//Encoder encoder = Base64.getEncoder();
		
		System.out.println(sp_id);
		PrintWriter out = response.getWriter();
		MYJSONObject result_jb = new MYJSONObject();
		
		
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String taskId=null;
		JSONArray second_project_all_ja=new JSONArray();
	//	ResultSetMetaData data =null;
		try {
			connection = JdbcUtils.getConnection();
			String sql = "insert into task(maintenanceplan_id,app_id_account,type,name,character,maintenance_project,status,code_chosed,create_time) values(?,?,?,?,?,?,?,?,?)";
			ps = connection.prepareStatement(sql);
			ps.setString(1, maintenanceplan_id);
			ps.setString(2, userId);
			ps.setString(3, task_type);
			ps.setString(4, task_name);
			ps.setString(5, task_character);
			ps.setString(6, project_id);
			ps.setString(7, "执行中");
			ps.setString(8, code_chosed);
			ps.setString(9, create_time);
			
		    ps.executeUpdate();
		   /* if( ps.executeUpdate()>0)
		    { */
					ps.close();
					sql ="select max(id) from task where task.app_id_account=? and task.type=? and task.name=? and maintenanceplan_id=?";
					ps = connection.prepareStatement(sql);
					ps.setString(1, userId);
					ps.setString(2, task_type);
					ps.setString(3, task_name);
					ps.setString(4, maintenanceplan_id);
					rs=ps.executeQuery();
			     	if(rs.next())
				    {
			        taskId=rs.getString(1);
			        }else 
				   {
					result_jb.put("status", "false");
					result_jb.put("message", "没找到最大id数据");
					System.out.print("没找到最大id数据");
				  }
					ps.close();
					rs.close();
					/*sql = "insert into task_maintenance_second(task_id,second_maintenance_id) values(?,?)";
					ps = connection.prepareStatement(sql);
					ps.setString(1, taskId);
					ps.setString(2, second_project_id);
					ps.executeUpdate();
					ps.close();
					rs.close();*/
					
					MYJSONObject second_project_all_jb=new MYJSONObject();
					for(int i=0;i<sp_id.size();i++)
					{
					sql = "select mtc.id,mtc.serial,mtc.test_name,mtc.test_content,mc.state_finished "
							+ "from maintenance_test_content mtc,task t,maintenanceplan m,maintenanceplan_content mc "
							+ "where t.id=? and m.id=? and m.id=mc.maintenanceplan_id and mc.state_finished='未完成' and mtc.id=mc.maintenance_content_id and mtc.Father_maintenance_id=? and m.state_finished='未完成'";
					ps = connection.prepareStatement(sql);
					ps.setString(1, taskId);
					ps.setString(2, maintenanceplan_id);
					ps.setString(3, sp_id.get(i));
					rs=ps.executeQuery();
					MYJSONObject test_jb=new MYJSONObject();
					JSONArray test_ja=new JSONArray();
					while(rs.next())
				    {	
			       test_jb.put("maintenance_test_content_id", rs.getString(1));
			       test_jb.put("maintenance_test_content_serial", rs.getString(2));
			       test_jb.put("maintenance_test_content_name", rs.getString(3));
			       test_jb.put("maintenance_test_content_all", rs.getString(4));
			       test_jb.put("maintenance_test_content_state_finished", rs.getString(5));
			       test_ja.add(test_jb.toString());
			        }
					second_project_all_jb.put("second_project_id", sp_id.get(i));
					second_project_all_jb.put("maintenance_content", test_ja);
					second_project_all_ja.add(second_project_all_jb.toString());
		  /*  }
		    else {
		    	result_jb.put("status", "false");
				result_jb.put("message", "未插入数据");
		    	System.out.print("未插入数据");
		    }*/
		} 
					result_jb.put("status", "true");
					result_jb.put("task_id", taskId);
					result_jb.put("message", second_project_all_ja);
		}catch (SQLException e) {
			e.printStackTrace();
			result_jb.put("status", "false");
			result_jb.put("message", "服务器异常");
		} finally {
			
			out.print(result_jb.toString());
			out.flush();
			out.close();
		}
	}

}
